# -*- coding: utf-8 -*-
def demoform():
    # form = FORM('Your name:', INPUT(_name='name'), INPUT(_type='submit'))
    # return dict(form=form)
    form = SQLFORM(db.alpha_factor, 3)
    # form = FORM('Your name:',
    # INPUT(_name='name', requires=IS_NOT_EMPTY()),
    # INPUT(_type='submit'))
    # if form.accepts(request, session):
    #     response.flash = 'form accepted'
    # elif form.errors:
    #     response.flash = 'form has errors'
    # else:
    #     response.flash = 'please fill the form'
    return dict(form=form)

def insertFactor():
    import time
    name = 'new node' + str(time.time())
    id=db.alpha_factor.insert(parent_id=request.vars.pid,name=name)
    return response.json({'status': 'ok','id':id,'name':name})

def updateFactor():
    db(db.alpha_factor.id == request.vars.id).update(name=request.vars.name)
    return response.json({'status': 'ok'})

def deleteFactor():
    db(db.alpha_factor.id == request.vars.id).delete()
    return response.json({'status': 'ok'})

def queryFactor():
    menuRows = db(db.alpha_factor.is_show == True).select(orderby=db.alpha_factor.sortno)
    list=[]
    for row in menuRows:
        list.append({"id": row.id, "pId": row.parent_id,"name":row.name})
    return list

def custom_fator_form():
    record = db.alpha_factor(request.get_vars.id)
    db.alpha_factor.parent_id.requires = IS_EMPTY_OR(IS_IN_DB(db(db.alpha_factor.parent_id==""or db.alpha_factor.parent_id==None), db.alpha_factor.id, '%(name)s'))
    # db.alpha_factor.memo.requires = IS_EMAIL(error_message='格式不正确')
    form = SQLFORM(db.alpha_factor,record, readonly=False, fields=[ 'name','parent_id','memo', 'sqlcodes'],labels = {'name':'因子名称：','parent_id':'  因子类别：','memo':'  因子描述：'},showid=False)
    if form.process().accepted:
        response.flash = 'form accepted'
    elif form.errors:
        response.flash = 'form has errors'
    return dict(form=form)

def custom_factor():
    return dict(factor=db(db.alpha_factor.is_show == True).select(orderby=db.alpha_factor.sortno))

def factor_desc():
    return dict(factor=db(db.alpha_factor.is_show == True).select(orderby=db.alpha_factor.sortno))

def factor_desc_form():
    record = db.alpha_factor(request.get_vars.id)
    form = SQLFORM(db.alpha_factor,record, readonly=False, fields=['memo', 'sqlcodes'],labels = {'memo':'  因子描述：'},showid=False)
    return dict(form=form)

def factor_change():
    return dict(factor=db(db.alpha_factor.is_show == True).select(orderby=db.alpha_factor.sortno))

def factor_change_form():
    record = db.alpha_factor(request.get_vars.id)
    db.alpha_factor.parent_id.requires = IS_EMPTY_OR(IS_IN_DB(db(db.alpha_factor.parent_id==""or db.alpha_factor.parent_id==None), db.alpha_factor.id, '%(name)s'))
    # db.alpha_factor.memo.requires = IS_EMAIL(error_message='格式不正确')
    form = SQLFORM(db.alpha_factor,record, readonly=False, fields=[ 'name','parent_id', 'calc'],labels = {'name':'目标因子：','parent_id':'  因子类别：','calc':'  计算公式：'},showid=False)
    if form.process().accepted:
        response.flash = 'form accepted'
    elif form.errors:
        response.flash = 'form has errors'
    return dict(form=form)


def wizard():
    stockpool = db(db.sys_dict.enumtype == 'stockpool').select(orderby=db.sys_dict.sortno)
    transcosts = db(db.sys_dict.enumtype == 'transcosts').select(orderby=db.sys_dict.sortno)
    hedgingfunc = db(db.sys_dict.enumtype == 'hedgingfunc').select(orderby=db.sys_dict.sortno)
    majorizfunc = db(db.sys_dict.enumtype == 'majorizfunc').select(orderby=db.sys_dict.sortno)
    trackerror = db(db.sys_dict.enumtype == 'trackerror').select(orderby=db.sys_dict.sortno)
    return dict(message=T('Welcome to web2py!'),stockpool_dict=stockpool,transcosts_dict=transcosts,hedgingfunc_dict=hedgingfunc,majorizfunc_dict=majorizfunc,trackerror_dict=trackerror)

def querywizard():
    list = sorted(generate_rand(20, 100))
    stock=db(db.alpha_stock_pool.id<300).select()
    import random
    slice = random.sample(stock, 10)
    name=""
    i=0
    for row in slice:
        i=i+1
        name=name+"<tr><td>"+str(i)+"</td><td>"+row.name+"</td><td>"+row.stockcode.zfill(6)+"</td><td>"+str(round(list[20-i*2],2))+"%</td></tr>"
    return response.json({'statrus': 'ok','name':name})

def generate_rand(n, sum_v):
    import random
    Vector = [random.random() for i in range(n)]
    Vector = [ (i / sum(Vector) * sum_v) for i in Vector]
    if sum(Vector) < sum_v:
        Vector[0] += sum_v-sum(Vector)
    return Vector

def mainwizard(policy_id=None,policy_name=None):
    stockpool = db(db.sys_dict.enumtype == 'stockpool').select(orderby=db.sys_dict.sortno)
    transcosts = db(db.sys_dict.enumtype == 'transcosts').select(orderby=db.sys_dict.sortno)
    hedgingfunc = db(db.sys_dict.enumtype == 'hedgingfunc').select(orderby=db.sys_dict.sortno)
    majorizfunc = db(db.sys_dict.enumtype == 'majorizfunc').select(orderby=db.sys_dict.sortno)
    trackerror = db(db.sys_dict.enumtype == 'trackerror').select(orderby=db.sys_dict.sortno)
    earningsforecast = db(db.sys_dict.enumtype == 'earningsforecast').select(orderby=db.sys_dict.sortno)
    return dict(message=T('Welcome to web2py!'),stockpool_dict=stockpool,transcosts_dict=transcosts,hedgingfunc_dict=hedgingfunc,majorizfunc_dict=majorizfunc,trackerror_dict=trackerror,earningsforecast_dict=earningsforecast,policy_id=policy_id,policy_name=policy_name)

def retest():
    id = request.get_vars['policy_id']
    return dict(message=T('Welcome to web2py!'),policy_id=id)

def mainwizard_v2():
    policy_id = request.get_vars['policy_id']
    policy_name = request.get_vars['policy_name']
    return mainwizard(policy_id,policy_name)

def perf_attrib():
    id = request.get_vars['policy_id']
    return dict(message=T('Welcome to web2py!'),policy_id=id)

def risk_attrib():
    id = request.get_vars['policy_id']
    return dict(message=T('Welcome to web2py!'),policy_id=id)

def policy_list():
    return dict(message=T('Welcome to web2py!'))

def alpha_limit():
    policy_id = request.get_vars['policy_id']
    return dict(message=T('Welcome to web2py!'),policy_id=policy_id)